package com.dayatang.product.webapp.action.email;

import javax.mail.MessagingException;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;

import com.dayatang.product.domain.EmailInfo;
import com.dayatang.product.webapp.action.BaseAction;
import com.dayatang.product.webapp.annotation.PMLog;

@ParentPackage(value = "web")
public class EmailConnectTestAction extends BaseAction {

	private static final long serialVersionUID = -7788976880235009731L;

	private EmailInfo emailInfo;
	
	private String result;
	
	@Action(results = {@Result(name = "success", type = "json")})
	@PMLog(moduleName = "邮箱管理", option = "测试邮箱有效性")
	public String execute() throws Exception {
		if (emailInfo != null) {
			emailInfo = EmailInfo.get(EmailInfo.class, emailInfo.getId());
			result = sendTestEmail(emailInfo);
			if (result.equals("邮箱测试成功！")) {
				emailInfo.setUsable(true);
				productApplication.saveEntity(emailInfo);
			}
		}
		return SUCCESS;
	}

	@JSON(serialize = false)
	public EmailInfo getEmailInfo() {
		return emailInfo;
	}

	public void setEmailInfo(EmailInfo emailInfo) {
		this.emailInfo = emailInfo;
	}
	
	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	private String sendTestEmail(EmailInfo emailInfo) {
		try {
			Email email = new SimpleEmail();
			email.setHostName(emailInfo.getSmtpName());
			email.setSmtpPort(emailInfo.getSmtpPort());
			email.setAuthenticator(new DefaultAuthenticator(emailInfo.getUsername(),emailInfo.getPassword()));
			email.setTLS(false);
			email.setFrom(emailInfo.getUsername());
			email.addTo("547531167@qq.com");
			email.setCharset(CHAREST);
			email.setSubject("大雅堂产品信息管理系统邮箱测试");
			email.buildMimeMessage();
			email.getMimeMessage().setText("来自大雅堂产品信息管理系统，This is a test mail.... :-)", CHAREST);
			email.sendMimeMessage();
			return "邮箱测试成功！";
		} catch (EmailException e) {
			return e.toString();
		} catch (MessagingException e) {
			return e.toString();
			
		} 
	}
}
